package com.maochd.platform.service.impl;

import com.maochd.platform.config.DingTalkConfig;
import com.maochd.platform.config.DingTalkConfig.Robot;
import com.maochd.platform.domain.DingTalk;
import com.maochd.platform.domain.DingTalkResp;
import com.maochd.platform.service.DingTalkService;
import com.maochd.platform.util.RestUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

@Service
public class DingTalkServiceImpl implements DingTalkService {

    @Resource
    private RestUtils restUtils;

    @Resource
    private DingTalkConfig dingTalkConfig;


    @SneakyThrows
    public void sendRobot(DingTalk dt) {
        Robot robot = dingTalkConfig.getRobotByName(dt.getRobotName());
        restUtils.postForJson(buildUrl(robot), dt, DingTalkResp.class);
    }

    @SneakyThrows
    private String sign(String secret) {
        Long timestamp = System.currentTimeMillis();
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        Base64.Encoder encoder = Base64.getEncoder();
        String sign = URLEncoder.encode(encoder.encodeToString(signData), "UTF-8");
        return "&timestamp=" + timestamp + "&sign=" + sign;
    }

    private String buildUrl(Robot robot) {
        return robot.getWebhookUrl() + sign(robot.getSecret());
    }
}
